/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof.wget;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Carlos Pinheiro
 */
public class DownloadersLauncher extends Thread
{
    private static final int WAIT_TIME = 1000;
    private static DownloadersLauncher lb = new DownloadersLauncher();
    private ExecutorService tpDownloaders = Executors.newCachedThreadPool();

    private DownloadersLauncher()
    {
    }

    public static DownloadersLauncher getInstance()
    {           
        return lb;
    }

    @Override
    public void run()
    {
        // Starts bandwith controller
        DownloadersBalancer.getInstance().start();
        
        try
        {
            tpDownloaders = Executors.newCachedThreadPool();
            while (!isInterrupted())
            {
                if (ToDownloadQueue.getInstance().isEmpty())
                {
                    Thread.sleep(WAIT_TIME);
                    continue;
                }
                
                Runnable downloader = new DownloaderExecutor();
                tpDownloaders.execute(downloader);               
            }
        }
        catch (InterruptedException ex)
        {            
        }
        finally
        {
            processInterruption();
        }
    }

    private void processInterruption()
    {
        try
        {
            DownloadersBalancer.getInstance().interrupt();
            DownloadersBalancer.getInstance().join();
            
            tpDownloaders.shutdown();
            tpDownloaders.awaitTermination(10, TimeUnit.SECONDS);
        } 
        catch (InterruptedException ex)
        {
        }
    }
}
